package com.study.ThreadPoolExecutor;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

public class AtomicIntegerTest {

	//创建原子类更新器, 设置需要的对象类和对象属性
	private static AtomicIntegerFieldUpdater<User> newUpdater = AtomicIntegerFieldUpdater.newUpdater(User.class, "age");
	
	public static void main(String[] args){
		AtomicInteger atomicInteger = new AtomicInteger(1);
		
		System.out.println("atomicInteger.getAndIncrement(): " + atomicInteger.getAndIncrement());  //1，返回原来的值
		System.out.println("自增后的atomicInteger: " + atomicInteger);  //2， 更新后的值
		
		System.out.println("atomicInteger.decrementAndGet(): " + atomicInteger.decrementAndGet()); //1, 返回更新后的值
		System.out.println("自减后的atomicInteger: " + atomicInteger); //1
		
		System.out.println("atomicInteger.getAndSet(10): " + atomicInteger.getAndSet(10)); //1
		System.out.println("getAndSet后的值: " + atomicInteger); //10
		
		//原子操作: 如果atomicInteger 当前值等于10，则将atomicInteger设置为2，并返回true
		System.out.println("atomicInteger.compareAndSet(10, 2) =" + atomicInteger.compareAndSet(10, 2));  //true
		System.out.println("atomicInteger：" + atomicInteger);//2
		System.out.println("atomicInteger.compareAndSet(11, 99) = " + atomicInteger.compareAndSet(11, 99)); //false
		System.out.println("atomicInteger：" + atomicInteger); //2
		
		User user = new User();
		user.setAge(10);
		user.setUserName("neo");
		System.out.println("newUpdater.getAndIncrement(user):" + newUpdater.getAndIncrement(user));  //10
		System.out.println("newUpdater.get(user):"+ newUpdater.get(user)); //11
	}
}

class User{
	private String userName;
	public volatile int age;
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}